<?php
namespace app\common\service;

use app\common\model\BaseModel;
use app\common\model\ChatUserInfoModel;
use app\common\model\OrderModel;
use app\common\model\SysSettingModel;
use app\common\model\UserModel;
use GuzzleHttp\Exception\RequestException;

//活动
class Paypal{
    public static function getUrl()
    {
        return Config::pay_paypal('debug')=='test'? 'https://api-m.sandbox.paypal.com' : 'https://api-m.paypal.com';
    }
    public static function getToken()
    {
        $debug = Config::pay_paypal('debug')=='test'?1:0;
        $url = self::getUrl()."/v1/oauth2/token";
        $cache_name = "paypal_token".$debug;
        $token = cache($cache_name);
        if(empty($token)){
            $data = self::req($url,"grant_type=client_credentials","POST",[
                'Authorization' => 'Basic '.base64_encode(Config::pay_paypal('client_id').":".Config::pay_paypal('secret')),
                'Content-Type' => 'application/x-www-form-urlencoded',
            ]);
            $token = $data['access_token'];
            cache($cache_name,$token,$data['expires_in']-3600);
        }
        return $token;
    }


    public static function backMoney(OrderModel $orderModel,$money)
    {
        $url = self::getUrl()."/v2/payments/captures/{$orderModel['paypal_capture_id']}/refund";
        $result = self::req($url,[
            'amount'=>[
                'value'=>sprintf('%.02d',$money),
                'currency_code'=>MaBangErp::CURRENCY,
            ],
            'invoice_id'=>$orderModel['no'],
            'note_to_payer'=>'Defective product',
        ]);
        $state = 0;
        if(!empty($result)){
            if(isset($result['status'])){
                if($result['status']=='PENDING'){
                    $state = 1;
                }elseif($result['status']=='COMPLETED'){
                    $state = 2;
                }
                $status_details = $result['status_details']??[];
                return [$result['status'],$state,json_encode($status_details),json_encode($result)];

            }elseif(isset($result['details'])){
                return [$result['name']??'',0,json_encode($result['details']),json_encode($result)];
            }

        }
        return ['',$state,'', json_encode($result)];
    }


    public static function checkout_orders($order_id,$order_no,$pay_money,$return_url,$cancel_url,$currency="USD")
    {
        $url = self::getUrl()."/v2/checkout/orders";
        $content = [
            "intent"=>"CAPTURE",
            "purchase_units"=>[
                [
                    "custom_id"=> $order_id,
                    "invoice_id"=> $order_no,
                    "amount"=>[
                        "currency_code"=>$currency,
                        "value"=>$pay_money,
                    ]
                ]
            ],
            "application_context"=>[
                "return_url"=>$return_url,
                "cancel_url"=>$cancel_url,
            ],
        ];
        $data = self::req($url,$content);

        return $data;
    }

    public static function checkout_order_capture($paypal_order_id)
    {
        $url = self::getUrl()."/v2/checkout/orders/$paypal_order_id/capture";
        $data = self::req($url,"");
        return $data;
    }

    public static function checkout_order_detail($paypal_order_id)
    {
        $url = self::getUrl()."/v2/checkout/orders/$paypal_order_id";
        $data = self::req($url,"",'GET');
        return $data;
    }

    public static function req($url,$data,$method="POST",array $headers = []){

        try{
            $client = new \GuzzleHttp\Client();
            $options = [
                'verify'=>false,
                'headers' => !empty($headers)?$headers:[
                    'Authorization' => 'Bearer '.self::getToken(),
                    'Content-Type' => 'application/json',
                ]
            ];
            if(is_array($data)){
                $options['json'] = $data;
            }else{
                $options['body'] = $data;

            }

            $response = $client->request($method, $url, $options);
            $result = $response->getBody()->getContents(); // '{"id": 1420053, "name": "guzzle", ...}'
        }catch (RequestException $e){
            $result = $e->getResponse()->getBody()->getContents();
        }catch (\Exception $e){
            $result = "{'errmsg':'{$e->getmessage()}'}";
        }

        $result = empty($result)?[]:json_decode($result,true);
        return $result;

    }

}